import { formatDate, findItemFromList } from '@/utils';
import * as StaticDict from '@/staticDict';
import rules from '@/utils/validate.js';
import { eventFunction } from '@/utils/onlineEvent.js';
import { getDictDataList } from './utils';

export const OnlineFormMixins = {
  data () {
    return {
      isReady: false,
      showSubPage: false,
      subFormId: undefined,
      editRowData: undefined,
      operationSender: undefined,
      operationCallback: undefined,
      errorMessage: [],
      tableWidgetList: [],
      dropdownWidgetList: [],
      richEditWidgetList: [],
      formData: {
        // 数据字段会根据render信息去初始化
        // 自定义字段
        customField: {}
      },
      rules: {},
      getDictDataList: getDictDataList,
      // 在线表单组件权限
      formAuth: undefined,
      widgetImplList: {}
    }
  },
  methods: {
    buildFormConfig (formData) {
      if (formData == null) return;
      let formConfig = formData;
      formConfig.datasourceMap = new Map();
      formConfig.relationMap = new Map();
      formConfig.tableMap = new Map();
      formConfig.columnMap = new Map();
      formConfig.dictMap = new Map();
      formConfig.linkageMap = new Map();
      let rawData = formData.rawData;
      if (rawData == null) return formConfig;
      // 字典
      if (Array.isArray(rawData.onlineDictList)) {
        rawData.onlineDictList.forEach(dict => {
          formConfig.dictMap.set(dict.dictId, dict);
        });
      }
      rawData.onlineDictList = null;
      // 数据表
      if (Array.isArray(rawData.onlineTableList)) {
        rawData.onlineTableList.forEach(table => {
          formConfig.tableMap.set(table.tableId, table);
        });
      }
      rawData.onlineTableList = null;
      // 字段
      if (Array.isArray(rawData.onlineColumnList)) {
        rawData.onlineColumnList.forEach(column => {
          if (column.dictId != null) {
            column.dictInfo = formConfig.dictMap.get(column.dictId);
          }
          if (column.encodedRule != null && column.encodedRule !== null) {
            column.encodedRule = JSON.parse(column.encodedRule);
          }
          // 脱敏设置
          if (Array.isArray(formConfig.maskFieldList) && formConfig.maskFieldList.length > 0) {
            formConfig.maskFieldList.forEach(item => {
              if (Array.isArray(item) && item.length === 2) {
                if (item[0] === column.tableId && item[1] === column.columnId) {
                  column.supportMaskField = true;
                }
              }
            });
          }
          // 是否富文本
          column.isRichText = column.fieldKind === this.SysOnlineFieldKind.RICH_TEXT;
          let table = formConfig.tableMap.get(column.tableId);
          if (table) {
            if (!Array.isArray(table.columnList)) table.columnList = [];
            table.columnList.push(column);
          }
          formConfig.columnMap.set(column.columnId, column);
        });
      }
      rawData.onlineColumnList = null;
      // 虚拟字段
      if (Array.isArray(rawData.onlineVirtualColumnList)) {
        rawData.onlineVirtualColumnList.forEach(column => {
          column.columnId = column.virtualColumnId;
          column.columnComment = column.columnPrompt;
          column.columnName = column.objectFieldName;
          column.primaryKey = false;
          column.isVirtualColumn = true;
          formConfig.columnMap.set(column.columnId, column);
        });
      }
      rawData.onlineVirtualColumnList = null;
      // 数据源
      if (Array.isArray(rawData.onlineDatasourceList)) {
        rawData.onlineDatasourceList.forEach(datasource => {
          datasource.masterTable = formConfig.tableMap.get(datasource.masterTableId);
          if (datasource.masterTable) datasource.masterTable.datasource = JSON.parse(JSON.stringify(datasource)); // fix 隐式深拷贝，解除循环引用
          formConfig.datasourceMap.set(datasource.datasourceId, datasource);
        });
      }
      rawData.onlineDatasourceList = null;
      // 关联
      if (Array.isArray(rawData.onlineDatasourceRelationList)) {
        rawData.onlineDatasourceRelationList.forEach(relation => {
          let datasource = formConfig.datasourceMap.get(relation.datasourceId);
          if (datasource) {
            if (!Array.isArray(datasource.relationList)) datasource.relationList = [];
            datasource.relationList.push(relation);
          }
          relation.masterColumn = formConfig.columnMap.get(relation.masterColumnId);
          relation.slaveTable = formConfig.tableMap.get(relation.slaveTableId);
          if (relation.slaveTable) {
            relation.slaveTable.relation = JSON.parse(JSON.stringify(relation)); // fix 隐式深拷贝，解除循环引用
            relation.slaveTable.datasource = JSON.parse(JSON.stringify(datasource)); // fix 隐式深拷贝，解除循环引用
          }
          relation.slaveColumn = formConfig.columnMap.get(relation.slaveColumnId);
          formConfig.relationMap.set(relation.relationId, relation);
        });
      }
      rawData.onlineDatasourceRelationList = null;
      // 校验规则
      if (Array.isArray(rawData.onlineColumnRuleList)) {
        rawData.onlineColumnRuleList.forEach(rule => {
          let column = formConfig.columnMap.get(rule.columnId);
          if (column) {
            if (!Array.isArray(column.ruleList)) column.ruleList = [];
            column.ruleList.push(rule);
          }
        });
      }
      rawData.onlineColumnRuleList = null;
      return formConfig;
    },
    getSystemVariableValue (systemVariableType) {
      switch (systemVariableType) {
        case this.OnlineSystemVariableType.CURRENT_USER: return this.getUserInfo.showName;
        case this.OnlineSystemVariableType.CURRENT_DEPT: return this.getUserInfo.deptName;
        case this.OnlineSystemVariableType.CURRENT_DATE: return formatDate(new Date(), 'YYYY-MM-DD');
        case this.OnlineSystemVariableType.CURRENT_TIME: return formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss');
        case this.OnlineSystemVariableType.FLOW_CREATE_USER: return (this.flowInfo || {}).processInstanceInitiator || this.getUserInfo.showName;
      }
      return undefined;
    },
    getWidgetValueByColumn (column) {
      if (column == null) return undefined;
      let table = column.tableId ? this.form.tableMap.get(column.tableId) : undefined;
      if (table == null || table.datasource == null) return undefined;
      return table.relation == null ? this.formData[table.datasource.variableName][column.columnName] : this.formData[table.relation.variableName][column.columnName];
    },
    getWidgetValue (widget, rowData) {
      let data = rowData || this.formData;
      // 列表组件
      if (widget.widgetType === this.SysCustomWidgetType.List) {
        // 返回从表数据
        if (widget.relation && data[widget.relation.variableName]) {
          return data[widget.relation.variableName];
        }
        return [];
      }
      if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Column && widget.column) {
        if (rowData != null) {
          if (this.formReadOnly || widget.widgetType === this.SysCustomWidgetType.Label || widget.widgetType === this.SysCustomWidgetType.Text) {
            let dictObj = (widget && widget.column && widget.column.columnName && data) ? data[widget.column.columnName + 'DictMap'] : null;
            if (dictObj != null && dictObj.name) return dictObj.name;
            let dictArray = data[widget.column.columnName + 'DictMapList'];
            if (Array.isArray(dictArray) && dictArray.length > 0) return dictArray.map(item => item.name).join(',');
          }
          return data[widget.column.columnName];
        }
        // 绑定从表字段
        if (widget.relation && data[widget.relation.variableName]) {
          if (this.formReadOnly || widget.widgetType === this.SysCustomWidgetType.Label || widget.widgetType === this.SysCustomWidgetType.Text) {
            let dictObj = data[widget.relation.variableName][widget.column.columnName + 'DictMap'];
            if (dictObj != null && dictObj.name) return dictObj.name;
            let dictArray = data[widget.relation.variableName][widget.column.columnName + 'DictMapList'];
            if (Array.isArray(dictArray) && dictArray.length > 0) return dictArray.map(item => item.name).join(',');
          }
          return data[widget.relation.variableName][widget.column.columnName];
        }
        // 绑定主表字段
        if (widget.datasource && data[widget.datasource.variableName]) {
          if (this.formReadOnly || widget.widgetType === this.SysCustomWidgetType.Label || widget.widgetType === this.SysCustomWidgetType.Text) {
            let dictObj = data[widget.datasource.variableName][widget.column.columnName + 'DictMap'];
            if (dictObj != null && dictObj.name) return dictObj.name;
            let dictArray = data[widget.datasource.variableName][widget.column.columnName + 'DictMapList'];
            if (Array.isArray(dictArray) && dictArray.length > 0) {
              let temp = dictArray.map(item => item.name).join(',');
              return temp;
            }
          }
          return data[widget.datasource.variableName][widget.column.columnName];
        }
      } else if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Custom && widget.bindData.formFieldName) {
        return this.formData.customField[widget.bindData.formFieldName];
      } else if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.SYSTEM_VARIABLE && widget.bindData.systemVariableType != null) {
        // 系统内置变量
        return this.getSystemVariableValue(widget.bindData.systemVariableType);
      }
    },
    getWidgetProp (widget, value) {
      if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Column && widget.column) {
        if (widget.relation && this.formData[widget.relation.variableName]) {
          return widget.relation.variableName + '.' + widget.column.columnName;
        } else if (widget.datasource && this.formData[widget.datasource.variableName]) {
          return widget.datasource.variableName + '.' + widget.column.columnName;
        }
      } else if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Custom && widget.bindData.formFieldName) {
        return 'customField.' + widget.bindData.formFieldName;
      }
    },
    onValueChange (widget, value) {
      if (this.formReadOnly) return;
      // 列表组件
      if (widget.widgetType === this.SysCustomWidgetType.List) {
        // 设置从表列表数据
        if (widget.relation) {
          this.formData[widget.relation.variableName] = value;
        }
        return;
      }
      if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Column && widget.column) {
        // 绑定从表字段
        if (widget.relation) {
          this.formData[widget.relation.variableName][widget.column.columnName] = value;
        }
        // 绑定主表字段
        if (widget.datasource) {
          this.formData[widget.datasource.variableName][widget.column.columnName] = value;
        }
      } else if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Custom && widget.bindData.formFieldName) {
        this.formData.customField[widget.bindData.formFieldName] = value;
      }
    },
    getWidgetVisible (widget) {
      if (this.isEdit) return true;
      let formWidgetAuth = this.formAuth && this.formAuth.mobile ? this.formAuth.mobile[widget.variableName] : null;
      if (formWidgetAuth && formWidgetAuth.hide) return false;
      if (widget.eventInfo && typeof widget.eventInfo[this.OnlineFormEventType.VISIBLE] === 'function') {
        return widget.eventInfo[this.OnlineFormEventType.VISIBLE]();
      } else {
        return true;
      }
    },
    getOperationPermCode (operation) {
      let temp = 'view';
      switch (operation.type) {
        case this.SysCustomWidgetOperationType.ADD:
        case this.SysCustomWidgetOperationType.EDIT:
        case this.SysCustomWidgetOperationType.DELETE:
        case this.SysCustomWidgetOperationType.BATCH_DELETE:
          temp = 'edit';
          break;
        default:
          temp = 'view';
      }
      if (this.masterTable && this.masterTable.datasource) {
        return 'online:' + this.masterTable.datasource.variableName + ':' + temp;
      } else {
        return '';
      }
    },
    getScriptFunction (eventInfo, eventType) {
      let sysInfo = uni.getSystemInfoSync();
      if (sysInfo.uniPlatform !== 'mp-weixin' && eventInfo && typeof eventInfo[eventType] === 'function') {
        return eventInfo[eventType];
      } else {
        return null;
      }
    },
    checkOperationPermCode (operation) {
      if (this.form.formType !== this.SysOnlineFormType.QUERY || this.isEdit) return true;
      return this.checkPermCodeExist(this.getOperationPermCode(operation));
    },
    checkOperationDisabled (operation, rowData) {
      if (this.isEdit) return false;
      if (operation == null) return true;
      let fun = this.getScriptFunction(operation.eventInfo, this.OnlineFormEventType.OPERATION_DISABLED);
      return fun ? fun(rowData) : false;
    },
    checkOperationVisible (operation, rowData) {
      if (this.isEdit) return true;
      if (operation == null) return false;
      let fun = this.getScriptFunction(operation.eventInfo, this.OnlineFormEventType.OPERATION_VISIBLE);
      return fun ? fun(rowData) : true;
    },
    onWidgetValueChange (widget, value, detail) {
      if (this.formReadOnly) return;
      let dictData = (detail || {}).dictData;
      // 更新字典数据
      if (dictData != null) {
        if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Column && widget.column) {
          // 绑定从表字段
          if (widget.relation) {
            if (Array.isArray(dictData)) {
              this.formData[widget.relation.variableName][widget.column.columnName + 'DictMapList'] = dictData;
            } else {
              this.formData[widget.relation.variableName][widget.column.columnName + 'DictMap'] = dictData;
            }
            let fun = this.getScriptFunction(widget.eventInfo, this.OnlineFormEventType.CHANGE);
            fun && fun(value, detail);
          }
          // 绑定主表字段
          if (widget.datasource) {
            if (Array.isArray(dictData)) {
              this.formData[widget.datasource.variableName][widget.column.columnName + 'DictMapList'] = dictData;
            } else {
              this.formData[widget.datasource.variableName][widget.column.columnName + 'DictMap'] = dictData;
            }
          }
        } else if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Custom && widget.bindData.formFieldName) {
          if (Array.isArray(dictData)) {
            this.formData.customField[widget.bindData.formFieldName + 'DictMapList'] = dictData;
          } else {
            this.formData.customField[widget.bindData.formFieldName + 'DictMap'] = dictData;
          }
        }
      }
      // 一对一关联选择组件
      if (widget.widgetType === this.SysCustomWidgetType.DataSelect &&
        (this.form.formType === this.SysOnlineFormType.FORM || this.form.formType === this.SysOnlineFormType.FLOW)) {
        let selectRow = (detail || {}).selectRow;
        let relationId = (widget.props.relativeTable || {}).relationId;
        let relation = this.form.relationMap.get(relationId);
        if (relation != null) {
          this.formData[relation.variableName] = selectRow || {};
        }
      }
      let fun = this.getScriptFunction(widget.eventInfo, this.OnlineFormEventType.CHANGE);
      fun && fun(value, detail);
    },
    getPrimaryData (widget, data) {
      let primaryKey;
      if (widget && widget.table && Array.isArray(widget.table.columnList)) {
        widget.table.columnList.forEach(column => {
          if (column.primaryKey) primaryKey = column.columnName;
        });
      }
      if (primaryKey != null) {
        let tempData;
        if (data != null) {
          tempData = widget.relation == null ? data : data[widget.relation.variableName];
        } else {
          tempData = widget.relation == null ? this.formData[widget.datasource.variableName] : this.formData[widget.relation.variableName];
        }
        if (tempData != null) {
          if (Array.isArray(tempData)) {
            return tempData[0][primaryKey]
          } else {
            return tempData[primaryKey];
          }
        }
      }
      return undefined;
    },
    initFormWidgetList () {
      if (Array.isArray(this.form.operationList)) {
        this.form.operationList.forEach(operation => {
          operation.eventInfo = (operation.eventList || []).reduce((retObj, event) => {
            let fun = eventFunction(event);
            if (fun) retObj[event.eventType] = fun.bind(this);
            return retObj;
          }, {});
        });
      }
      if (Array.isArray(this.form.formEventList)) {
        this.form.eventInfo = this.form.formEventList.reduce((retObj, event) => {
          let fun = eventFunction(event);
          if (fun) retObj[event.eventType] = fun.bind(this);
          return retObj;
        }, {});
      } else {
        this.form.eventInfo = {};
      }
      this.errorMessage = [];
      if (Array.isArray(this.form.widgetList)) {
        this.form.widgetList.forEach(widget => {
          this.initWidget(widget);
        });
      }
      if (this.form.tableWidget) {
        this.initWidget(this.form.tableWidget);
        this.form.tableWidget.table = this.masterTable;
        if (this.form.tableWidget.table) {
          if (this.form.tableWidget.table.datasource) this.form.tableWidget.datasource = this.form.tableWidget.table.datasource;
          if (this.form.tableWidget.table.relation) this.form.tableWidget.relation = this.form.tableWidget.table.relation;
        }
      }
      if (this.form.leftWidget) this.initWidget(this.form.leftWidget);
      if (this.errorMessage.length > 0) {
        console.error(this.errorMessage);
      }
    },
    initWidget (widget) {
      if (widget != null) {
        if (widget.bindData.tableId) widget.table = this.form.tableMap.get(widget.bindData.tableId);
        if (widget.bindData.columnId) widget.column = this.form.columnMap.get(widget.bindData.columnId);
        if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Custom) {
          if (widget.props.dictId != null) {
            widget.dictInfo = this.form.dictMap.get(widget.props.dictId);
          }
        } else {
          widget.dictInfo = (widget.column || {}).dictInfo;
        }
        if (widget.table) {
          if (widget.table.datasource) widget.datasource = widget.table.datasource;
          if (widget.table.relation) widget.relation = widget.table.relation;
        }
        if (widget.widgetType === this.SysCustomWidgetType.RichEditor) {
          this.richEditWidgetList.push(widget);
        }
        widget.propString = this.getWidgetProp(widget);

        // 初始化组件下拉字典参数
        if (widget.props.dictInfo && Array.isArray(widget.props.dictInfo.paramList)) {
          widget.props.dictInfo.paramList.forEach(param => {
            if (param.dictValueType === this.SysOnlineParamValueType.STATIC_DICT) {
              let errorItem = null;
              if (Array.isArray(param.dictValue) && param.dictValue.length === 2) {
                let staticDict = StaticDict[param.dictValue[0]];
                if (staticDict == null) {
                  errorItem = {
                    widget: widget,
                    message: '组件字典参数' + param.dictParamName + '绑定的静态字典 [' + param.dictValue[0] + '] 并不存在！'
                  }
                } else {
                  if (staticDict.getValue(param.dictValue[1]) == null) {
                    errorItem = {
                      widget: widget,
                      message: '组件字典参数' + param.dictParamName + '绑定的静态字典值并不属于静态字段 [' + param.dictValue[0] + '] ！'
                    }
                  }
                }
              } else {
                errorItem = {
                  widget: widget,
                  message: '组件字典参数' + param.dictParamName + '绑定的静态字典错误！'
                }
              }
              if (errorItem != null) this.errorMessage.push(errorItem);
            }
          });
        }
        if (widget.props.dictInfo && widget.props.dictInfo.dictId) {
          widget.props.dictInfo.dict = this.form.dictMap.get(widget.props.dictInfo.dictId);
        }
        if (widget.column && widget.column.dictInfo != null) {
          this.dropdownWidgetList.push(widget);
        }
        // 初始化表格列
        if (widget.widgetType === this.SysCustomWidgetType.Table || widget.widgetType === this.SysCustomWidgetType.List) {
          // 寻找表格主键
          widget.primaryColumnName = undefined;
          if (widget.table && Array.isArray(widget.table.columnList)) {
            for (let i = 0; i < widget.table.columnList.length; i++) {
              if (widget.table.columnList[i].primaryKey) {
                widget.primaryColumnName = widget.table.columnList[i].columnName;
                break;
              }
            }
          }
          if (Array.isArray(widget.props.tableColumnList)) {
            widget.props.tableColumnList.forEach(tableColumn => {
              tableColumn.table = this.form.tableMap.get(tableColumn.tableId);
              tableColumn.column = this.form.columnMap.get(tableColumn.columnId);
              tableColumn.relation = this.form.relationMap.get(tableColumn.relationId);
              if (tableColumn.table == null || tableColumn.column == null) {
                this.errorMessage.push({
                  widget: widget,
                  message: '表格列 [' + tableColumn.showName + '] 绑定的字段不存在！'
                });
              }
            });
          }
          // 操作排序
          if (Array.isArray(widget.operationList)) {
            widget.operationList = (widget.operationList || []).sort((value1, value2) => {
              return (value1.showOrder || 0) - (value2.showOrder || 0)
            });
            widget.operationList.forEach(operation => {
              operation.eventInfo = (operation.eventList || []).reduce((retObj, event) => {
                let fun = eventFunction(event);
                if (fun) retObj[event.eventType] = fun.bind(this);
                return retObj;
              }, {});
            });
          }
          this.tableWidgetList.push(widget);
        }

        if (Array.isArray(widget.childWidgetList)) {
          widget.childWidgetList.forEach(subWidget => {
            this.initWidget(subWidget);
          })
        }

        if (widget.props && widget.props.dictInfo) {
          if (Array.isArray(widget.props.dictInfo.paramList)) {
            widget.props.dictInfo.paramList.forEach(dictParam => {
              if (dictParam.dictValueType === this.SysOnlineParamValueType.TABLE_COLUMN) {
                let linkageItem = this.form.linkageMap.get(dictParam.dictValue);
                if (linkageItem == null) {
                  linkageItem = [];
                  this.form.linkageMap.set(dictParam.dictValue, linkageItem);
                }
                linkageItem.push(widget);
              }
            });
          }
        }

        if (Array.isArray(widget.eventList)) {
          widget.eventInfo = widget.eventList.reduce((retObj, event) => {
            let fun = eventFunction(event);
            if (fun) retObj[event.eventType] = fun.bind(this);
            return retObj;
          }, {});
        } else {
          widget.eventInfo = {};
        }
      }
    },
    buildRuleItem (column, rule, trigger = 'blur') {
      if (rule.propDataJson) rule.data = JSON.parse(rule.propDataJson);
      if (column != null && rule != null) {
        switch (rule.onlineRule.ruleType) {
          case this.SysOnlineRuleType.INTEGER_ONLY:
            return { type: 'integer', message: rule.data.message, trigger: trigger, transform: (value) => Number(value) };
          case this.SysOnlineRuleType.DIGITAL_ONLY:
            return { type: 'number', message: rule.data.message, trigger: trigger, transform: (value) => Number(value) };
          case this.SysOnlineRuleType.LETTER_ONLY:
            return { type: 'string', pattern: rules.pattern.english, message: rule.data.message, trigger: trigger };
          case this.SysOnlineRuleType.EMAIL:
            return { type: 'email', message: rule.data.message, trigger: trigger };
          case this.SysOnlineRuleType.MOBILE:
            return { type: 'string', pattern: rules.pattern.mobie, message: rule.data.message, trigger: trigger };
          case this.SysOnlineRuleType.RANGE:
            if (column) {
              let isNumber = ['Boolean', 'Date', 'String'].indexOf(column.objectFieldType) === -1;
              return { type: isNumber ? 'number' : 'string', min: rule.data.min, max: rule.data.max, message: rule.data.message, trigger: trigger };
            }
            break;
          case this.SysOnlineRuleType.CUSTOM:
            return { type: 'string', pattern: new RegExp(rule.onlineRule.pattern), message: rule.data.message, trigger: trigger };
        }
      }
    },
    buildWidgetRule (widget, rules) {
      const _this = this;
      if (widget != null) {
        let widgetRuleKey;
        if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Custom) {
          // 自定义字段
          widgetRuleKey = 'customField.' + widget.bindData.formFieldName;
        } else if (widget.bindData.dataType === this.SysCustomWidgetBindDataType.Column && widget.column) {
          // 绑定字段
          widgetRuleKey = (widget.relation ? widget.relation.variableName : widget.datasource.variableName) + '.' + widget.column.columnName;
        }
        // 必填字段以及设置了验证规则的字段
        if (widgetRuleKey && (widget.props.required || (widget.column && Array.isArray(widget.column.ruleList)))) {
          rules[widgetRuleKey] = [];
          // 必填验证
          if (widget.props.required) {
            rules[widgetRuleKey].push(
              { 
                required: true,
                type: 'string',
                message: widget.showName + '不能为空！',
                trigger: 'change', 
                transform(value) {
                  const widgetValue = _this.getWidgetValue(widget);
                  if (widgetValue == null) return undefined;
                  return widgetValue.toString();
                }
              }
            )
          }
          // 其他验证
          if (widget.column && Array.isArray(widget.column.ruleList)) {
            widget.column.ruleList.forEach(rule => {
              let ruleItem = this.buildRuleItem(widget.column, rule, 'change');
              if (ruleItem) rules[widgetRuleKey].push(ruleItem);
            });
          }
        }
        if (Array.isArray(widget.childWidgetList)) {
          widget.childWidgetList.forEach(subWidget => {
            this.buildWidgetRule(subWidget, rules);
          });
        }
      }
    },
    initWidgetRule () {
      let rules = {};
      this.form.widgetList.forEach(widget => {
        this.buildWidgetRule(widget, rules);
      });
      this.$set(this, 'rules', rules);
      setTimeout(() => {
        console.log('set Rules', this.$refs, this.$refs.form, this.rules);
        if (this.$refs.form) this.$refs.form.setRules(this.rules);
      }, 200);
    },
    resetWidget (widget) {
      const widgetImpl = this.widgetImplList[(widget || {}).variableName];
      if (widgetImpl && typeof widgetImpl.reset === 'function') {
        widgetImpl.reset();
        this.onValueChange(widget, undefined);
      }
    },
    initWidgetLinkage () {
      this.form.linkageMap.forEach((widgetList, key) => {
        let column = this.form.columnMap.get(key);
        let table = column ? this.form.tableMap.get(column.tableId) : undefined;
        let watchKey = 'formData.' + (table.relation == null ? table.datasource.variableName : table.relation.variableName) + '.';
        watchKey += column.columnName;
        this.$watch(watchKey, (newValue) => {
          if (Array.isArray(widgetList)) {
            widgetList.forEach(widget => {
              this.resetWidget(widget);
            });
          }
        });
      });
    },
    getParamValue (valueType, valueData) {
      switch (valueType) {
        case this.SysOnlineParamValueType.TABLE_COLUMN:
        {
          let column = this.form.columnMap ? this.form.columnMap.get(valueData) : null;
          return column ? this.getWidgetValueByColumn(column) : undefined;
        }
        case this.SysOnlineParamValueType.STATIC_DICT:
          return Array.isArray(valueData) ? valueData[1] : undefined;
        case this.SysOnlineParamValueType.INPUT_VALUE:
          return valueData;
      }
    },
    getDropdownParams (widget) {
      if (Array.isArray(widget.props.dictInfo.paramList)) {
        let params = {};
        for (let i = 0; i < widget.props.dictInfo.paramList.length; i++) {
          let dictParam = widget.props.dictInfo.paramList[i];
          if (dictParam.dictValue == null || dictParam.dictValueType == null) continue;
          params[dictParam.dictParamName] = this.getParamValue(dictParam.dictValueType, dictParam.dictValue);
        }

        return params;
      } else {
        return {};
      }
    },
    // 获取表忽略脱敏字段列表
    getTableIgnoreFieldList (table, ignoreList = []) {
      if (table == null) return;
      if (Array.isArray(table.columnList) && table.columnList.length > 0) {
        table.columnList.forEach(column => {
          if (!column.supportMaskField && column.fieldKind === this.SysOnlineFieldKind.FIELD_MASK) {
            ignoreList.push(table.tableName + '.' + column.columnName);
          }
        });
      }
    },
    getIgnoreMaskFields (widget) {
      let tempList = [];
      if (widget == null) {
        // 返回所有忽略字段
        this.form.tableMap.forEach(table => {
          this.getTableIgnoreFieldList(table, tempList);
        });
      } else {
        if (widget.relation == null) {
          if (widget.datasource){
            // 组件绑定的主表，返回主表以及一对一从表忽略字段
            this.getTableIgnoreFieldList(widget.datasource.masterTable, tempList);
          }
          if (widget.datasource && Array.isArray(widget.datasource.relationList)) {
            widget.datasource.relationList.forEach(relation => {
              if (relation.relationType === this.SysOnlineRelationType.ONE_TO_ONE) {
                this.getTableIgnoreFieldList(relation.slaveTable, tempList);
              }
            });
          }
        } else {
          // 组件绑定的从表，仅返回从表的忽略字段
          this.getTableIgnoreFieldList(widget.relation.slaveTable, tempList);
        }
      }
      return tempList.length > 0 ? tempList.join(',') : undefined;
    },
    initPage () {
      this.form.tableMap.forEach((table) => {
        if (table.relation == null) {
          // 主表
          let tempObj = Array.isArray(table.columnList) ? table.columnList.reduce((retObj, column) => {
            retObj[column.columnName] =
              column.objectFieldType === 'Boolean' ? false : undefined;
            return retObj;
          }, {}) : {};
          this.$set(this.formData, table.datasource.variableName, tempObj);
        } else {
          if (table.relation.relationType === this.SysOnlineRelationType.ONE_TO_ONE) {
            // 一对一关联从表
            let tempObj = Array.isArray(table.columnList) ? table.columnList.reduce((retObj, column) => {
              retObj[column.columnName] =
                column.objectFieldType === 'Boolean' ? false : undefined;
              return retObj;
            }, {}) : {};
            this.$set(this.formData, table.relation.variableName, tempObj);
          } else if (table.relation.relationType === this.SysOnlineRelationType.ONE_TO_MANY) {
            // 一对多关联从表
            if (this.masterTable.relation != null && this.masterTable.relation.relationId === table.relation.relationId) {
              // 表单主表是当前一对多从表
              let tempObj = Array.isArray(table.columnList) ? table.columnList.reduce((retObj, column) => {
                retObj[column.columnName] = undefined;
                return retObj;
              }, {}) : {};
              this.$set(this.formData, table.relation.variableName, tempObj);
            } else {
              this.$set(this.formData, table.relation.variableName, []);
            }
          }
        }
      });
      // 初始化自定义字段
      if (Array.isArray(this.form.customFieldList)) {
        this.form.customFieldList.forEach(field => {
          this.$set(this.formData.customField, field.fieldName, undefined);
        });
      }
    },
    hasOperator (type) {
      let temp = this.getOperation(type);
      return temp && temp.enabled;
    },
    getOperation (type) {
      return findItemFromList(this.form.operationList, type, 'type');
    },
    operationVisible (type) {
      let operation = this.getOperation(type);
      return !this.form.readOnly && this.hasOperator(type) && this.checkOperationVisible(operation);
    },
    onRefresh () {},
    handlerOperation (operation, data, sender, callback) {
      if (operation.type === this.SysCustomWidgetOperationType.BATCH_DELETE) {
        // 批量删除操作
        this.batchDelete(data);
      } else if (operation.type === this.SysCustomWidgetOperationType.DELETE) {
        // 批量删除操作
        this.deleteRow(data);
      } else {
        // 增、改查看详情操作
        this.handlerForm(operation, data, sender, callback);
      }
    },
    // 批量删除表格数据
    batchDelete (batchDeleteRows) {
      let table = this.queryTable.table;
      let params = {
        datasourceId: table.datasource.datasourceId,
        relationId: (table.relation || {}).relationId,
        dataIdList: batchDeleteRows.map(item => {
          return item[(table.primaryKeyColumn || {}).columnName];
        })
      }

      let httpCall;
			if (params.relationId) {
				httpCall = this.doUrl('/admin/online/onlineOperation/deleteBatchOneToManyRelation/' + table.datasource.variableName, 'post', params);
			} else {
				httpCall = this.doUrl('/admin/online/onlineOperation/deleteBatchDatasource/' + table.datasource.variableName, 'post', params);
			}
      httpCall.then(res => {
				uni.showToast({
					icon: 'success',
					title: '删除成功！'
				})
        this.onRefresh();
      }).catch(e => {
      });
    },
    // 删除数据
    deleteRow (row) {
      let table = this.queryTable.table;
      let params = {
        datasourceId: table.datasource.datasourceId,
        relationId: (table.relation || {}).relationId,
        dataId: row[(table.primaryKeyColumn || {}).columnName]
      }
      let httpCall = null;
      if (params.relationId) {
        httpCall = this.doUrl('/admin/online/onlineOperation/deleteOneToManyRelation/' + table.datasource.variableName, 'post', params);
      } else {
        httpCall = this.doUrl('/admin/online/onlineOperation/deleteDatasource/' + table.datasource.variableName, 'post', params);
      }

      httpCall.then(res => {
        uni.showToast({
          icon: 'success',
          title: '删除成功！'
        })
        this.refreshTable(true);
      }).catch(e => {});
    },
    // 页面操作
    handlerForm (operation, row, sender, callback) {
      let formId = operation.formId;
			// console.log(formId)
      if (formId == null) {
				uni.showToast({
					icon: 'error',
					title: '操作绑定表单不存在！'
				})
        return;
      }
      this.showSubPage = true;
      this.subFormId = operation.formId;
      this.editRowData = row || null;
      this.operationSender = sender;
      this.operationCallback = callback;
    },
    getQueryParams (filterWidgetList) {
      if (Array.isArray(filterWidgetList)) {
        return filterWidgetList.map(widget => {
          if (widget.bindData.dataType !== this.SysCustomWidgetBindDataType.Column || widget.column == null) return;
          let column = widget.column;
          let paramValue = this.getWidgetValue(widget);
          if (paramValue == null || paramValue === '' || (Array.isArray(paramValue) && paramValue.length === 0)) return;
          let temp = {
            tableName: widget.table.tableName,
            columnName: widget.column.columnName,
            filterType: widget.column.filterType,
            columnValue: widget.column.filterType !== this.SysOnlineColumnFilterType.RANFGE_FILTER ? paramValue : undefined
          }
          if (column.filterType === this.SysOnlineColumnFilterType.RANFGE_FILTER) {
            temp.columnValueStart = paramValue[0]
            temp.columnValueEnd = paramValue[1]
          }

          return temp;
        }).filter(item => item != null)
      }
      return []
    },
    getFormWidget() {
      return this.$refs ? this.$refs.form : null;
    },
    showMessage(type, message) {
      uni.showToast({
        icon: type,
        title: message
      });
    }
  },
  computed: {
    masterTable () {
      return this.form.tableMap.get(this.form.masterTableId)
    },
    isRelation () {
      return this.masterTable.relation != null
    },
    formReadOnly () {
      return this.readOnly || false
    },
    getUserInfo() {
      return uni.getStorageSync('userInfo');
    }
  }
}
